/*
 * Copyright (c) 2006-2025, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-05-08     RT-Thread    first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <stdlib.h>
#include <time.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#include "board.h"

int main(void)
{
//    int count = 1;
//
//    while (count++)
//    {
//        LOG_D("Hello RT-Thread!");
//        rt_thread_mdelay(1000);
//    }

    return RT_EOK;
}

/*
** 程序清单：这是一个 RTC 设备使用例程
** 例程导出了 alarm_sample 命令到控制终端
** 命令调用格式：alarm_sample
** 程序功能：设置RTC时间，创建闹钟，模式：每秒触发，启动闹钟
**/

void user_alarm_callback(rt_alarm_t alarm, time_t timestamp)
{
    rt_kprintf("user alarm callback function.\n");
}

void alarm_sample(void)
{
//  设置RTC时间，
    set_time(00, 00, 00);//北京时间，alarm为UTC时间
//  配置Alarm闹钟
    time_t now;
    struct tm timeinfo;
    rt_device_t rtc_dev = rt_device_find("rtc");
    if (rtc_dev == RT_NULL)
    {
        rt_kprintf("Find RTC device failed!\n");
        return;
    }

    rt_device_open(rtc_dev, RT_DEVICE_OFLAG_RDWR);

    rt_err_t result = rt_device_control(rtc_dev, RT_DEVICE_CTRL_RTC_GET_TIME, &now);
    if (result != RT_EOK)
    {
        rt_kprintf("Get RTC time failed! Error code: %d\n", result);
        rt_device_close(rtc_dev);
        return;
    }
//  RTC闹钟设置为本地时间可以触发，但是alarm线程会将时间改为UTC时间，所以建议使用UTC时间设置闹钟，这样可以将时间统一。
    gmtime_r(&now, &timeinfo);//UTC时间0时
//    localtime_r(&now, &timeinfo);//本地北京时间8时

    rt_kprintf("timeinfo time: %04d-%02d-%02d %02d:%02d:%02d\n",
               timeinfo.tm_year + 1900,  // tm_year是从1900年开始计算的
               timeinfo.tm_mon + 1,      // tm_mon是从0开始的，所以要加1
               timeinfo.tm_mday,
               timeinfo.tm_hour,
               timeinfo.tm_min,
               timeinfo.tm_sec);


    struct rt_alarm_setup setup;
    struct rt_alarm * alarm = RT_NULL;

    setup.flag = RT_ALARM_SECOND;
    setup.wktime.tm_year = timeinfo.tm_year;
    setup.wktime.tm_mon = timeinfo.tm_mon;
    setup.wktime.tm_mday = timeinfo.tm_mday;
    setup.wktime.tm_wday = timeinfo.tm_wday;
    setup.wktime.tm_hour = timeinfo.tm_hour;
    setup.wktime.tm_min = timeinfo.tm_min;
    setup.wktime.tm_sec = timeinfo.tm_sec;



    alarm = rt_alarm_create(user_alarm_callback, &setup);
    if(RT_NULL != alarm)
    {
        rt_alarm_start(alarm);
    }


    rt_kprintf("net time: %02d:%02d:%02d\n",
            alarm->wktime.tm_hour,
            alarm->wktime.tm_min,
            alarm->wktime.tm_sec);

}
/* export msh cmd */
MSH_CMD_EXPORT(alarm_sample,alarm sample);



